package com.alibaba.citrus.cr.sales.plan.facade.service.setting;

import com.alibaba.acm.shaded.com.google.common.collect.Maps;
import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.constant.OrganizationConstants;
import com.alibaba.citrus.cr.common.model.ImportRequest;
import com.alibaba.citrus.cr.common.model.epoch.EpochQueryPlanScItemScopeCrossDomainMatchReq;
import com.alibaba.citrus.cr.common.model.epoch.EpochQueryPlanScItemScopeCrossDomainMatchResp;
import com.alibaba.citrus.cr.common.util.EpochRESTClient;
import com.alibaba.citrus.cr.sales.plan.api.setting.SalesPlanScItemFileService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanScItemImportRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanOutCommonService;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.BatchQueryCompany2Request;
import com.epoch.app.bcorder.model.dto.CategorySDO;
import com.epoch.app.bcorder.model.dto.CompanySDO;
import com.epoch.app.bcorder.model.dto.QueryCategoryInfoByIdsRequest;
import com.epoch.app.bcorder.model.dto.ScItemSDO;
import com.epoch.app.bcorder.sales_plan.salesplanscitem.dto.BatchCreateSalesPlanScItemRequest;
import com.epoch.app.bcorder.sales_plan.salesplanscitem.dto.BatchCreateSalesPlanScItemResponse;
import com.epoch.app.bcorder.sales_plan.salesplanscitem.dto.SalesPlanScItemLoadListRequest;
import com.epoch.app.bcorder.sales_plan.salesplanscitem.model.SalesPlanScItem;
import com.epoch.app.bcorder.sales_plan.salesplanscitem.service.SalesPlanScItemService;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.crplatformenhance.api.customersalescopequery.service.CustomerSaleScopeQueryService;
import com.epoch.app.crplatformenhance.api.organizationquery.dto.BatchQuerySuperiorSalesOrganizationRequest;
import com.epoch.app.crplatformenhance.api.organizationquery.service.OrganizationQueryService;
import com.epoch.app.crplatformenhance.dto.request.IdQueryRequest;
import com.epoch.app.crplatformenhance.dto.request.QuerySaleScopeRequest;
import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.crplatformenhance.model.dto.QuerySuperiorSalesOrganizationResponse;
import com.epoch.app.crplatformenhance.sdo.CustomerSaleScopeSDO;
import com.epoch.app.crplatformenhance.sdo.OrganizationSDO;
import com.epoch.app.crpricecenter.api.pricequery.service.PriceQueryService;
import com.epoch.app.crpricecenter.dto.request.DimensionPropertyInfoRequest;
import com.epoch.app.crpricecenter.dto.request.HumanInfoRequest;
import com.epoch.app.crpricecenter.dto.request.MaterialInfoRequest;
import com.epoch.app.crpricecenter.dto.request.PlaceInfoRequest;
import com.epoch.app.crpricecenter.dto.request.PriceQueryRequest;
import com.epoch.app.crpricecenter.dto.response.ItemPriceResponse;
import com.epoch.app.crpricecenter.dto.response.PriceQueryResponse;
import com.epoch.app.crpricecenter.model.enums.PriceTypeEnum;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.alibaba.citrus.cr.common.constant.EpochRESTPathConstants.QUERY_PLAN_SCITEM_SCOPE_CROSS_DOMAIN_MATCH;

/**
 * @author wangyibing
 */
@Component
public class SalesPlanScItemFileServiceImpl implements SalesPlanScItemFileService {
    private final Log log = Log.getLogger(SalesPlanScItemFileServiceImpl.class);

    @Autowired
    private EpochRESTClient epochRESTClient;

    @Resource
    private SalesPlanOutCommonService salesPlanOutCommonService;

    @Resource
    private SalesPlanScItemService salesPlanScItemService;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private OrganizationQueryService organizationQueryService;

    @Resource
    private BcOrderService bcOrderService;

    @Resource
    private PriceQueryService priceQueryService;

    @Resource
    private CustomerSaleScopeQueryService customerSaleScopeQueryService;

    @Override
    @FacadeInvoker
    public Result<List<SalesPlanScItemImportRequest>> salesPlanScItemImport(List<SalesPlanScItemImportRequest> requestList, String orgBussinessUnitCode) {
        if (CollectionUtils.isEmpty(requestList)) {
            return Result.success(Lists.newArrayList());
        }
        //orgBusinessUnitCode为空说明登录人不是调度员
//        if (Strings.isBlank(orgBussinessUnitCode)) {
//            return Result.fail(ImportRequest.setRequestErrorMessage(requestList, ErrorMessage.code("OTS-01-003-01-15-015", null).getDisplayErrorMessage()),"OTS-01-003-01-15-015", ErrorMessage.code("OTS-01-003-01-15-015", null).getDisplayErrorMessage());
//        }
        //进一步判断员工的业务单元是否存在
//        IdQueryRequest idQueryRequest = new IdQueryRequest();
//        idQueryRequest.setId(orgBussinessUnitCode);
//        idQueryRequest.setType(OrganizationTypeEnum.COMPANY.getCode());
//        Result<List<OrganizationSDO>> userOrg =  organizationQueryService.getTopOrganizationList(idQueryRequest);
//        if (userOrg == null || CollectionUtils.isEmpty(userOrg.getResult())) {
//            return Result.fail(ImportRequest.setRequestErrorMessage(requestList, ErrorMessage.code("OTS-01-003-01-15-020", null).getDisplayErrorMessage()), "OTS-01-003-01-15-020", ErrorMessage.code("OTS-01-003-01-15-020", null).getDisplayErrorMessage());
//        }
//        Optional<String> userOrgBussinessUnitOutCode = userOrg.getResult().stream().findFirst().map(OrganizationSDO::getCode);

        Set<String> orgBusinessUnitCodes = requestList.stream().map(SalesPlanScItemImportRequest::getOrgBusinessUnitCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> orgSalesOrganizationCodes = requestList.stream().map(SalesPlanScItemImportRequest::getOrgSalesOrganizationCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> orgSalesChannelCodes = requestList.stream().map(SalesPlanScItemImportRequest::getOrgSalesChannelCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> scItemCodes = requestList.stream().filter(x->StringUtils.isNotBlank(x.getScItemId())).map(x->x.getScItemId().trim()).collect(Collectors.toSet());

        Set<String> codes = Sets.newHashSet();
        codes.addAll(orgBusinessUnitCodes);
        codes.addAll(orgSalesOrganizationCodes);
        codes.addAll(orgSalesChannelCodes);
        Map<String, com.epoch.app.crplatformenhance.sdo.OrganizationSDO> organizationMapByOutCode = salesPlanOutCommonService.getOrganizationMapByOutCode(codes);
        //所有组织都映射不上，不存在
        if (Objects.isNull(organizationMapByOutCode)) {
            return Result.success(ImportRequest.setRequestErrorMessage(requestList, ErrorMessage.code("OTS-01-003-01-16-003").getDisplayErrorMessage()));
        }
        //所有货品都找不到
        Map<String, ScItemSDO> scItemMap = salesPlanOutCommonService.getScItemMapByOutId(scItemCodes);
        if (Objects.isNull(scItemMap)) {
            return Result.success(ImportRequest.setRequestErrorMessage(requestList, ErrorMessage.code("OTS-01-005-02-15-001").getDisplayErrorMessage()));
        }

        //查询价格  获取分子公司组织
        List<SalesPlanScItemImportRequest> noPriceRequest = requestList.stream().filter(x->StringUtils.isBlank(x.getCostInsuranceFreight()) || StringUtils.isBlank(x.getOutboundPrice())).collect(Collectors.toList());
        Set<String> orgBusinessUnitCodeList = noPriceRequest.stream().map(SalesPlanScItemImportRequest::getOrgBusinessUnitCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        List<OrganizationSDO> orgBusinessUnitSDOList = organizationMapByOutCode.values().stream().filter(x->orgBusinessUnitCodeList.contains(x.getOutCode())).collect(Collectors.toList());

        //查询价格 售达方  <companyOrgCode,CustomerSaleScopeSDO>
        Map<String,CustomerSaleScopeSDO> customerSaleScopeMap = batchGetCustomerSaleScope(orgBusinessUnitSDOList);
        log.info("salesPlanScItemFileServiceImpl_salesPlanScItemImport_getCustomerSaleScopeMap_size={},queryOrgList_size={}",customerSaleScopeMap.size(),noPriceRequest.size());

        //查询价格 分子公司对应的总部销售组织
        Map<String,String> superiorSalesOrgRelationMap = batchGetSuperiorSalesOrg(orgBusinessUnitCodeList);

        List<SalesPlanScItem> addRequest = Lists.newArrayList();
        List<SalesPlanScItem> updateRequest = Lists.newArrayList();

        // 校验分子公司创建计划货品不可超出总部设置范围
        List<EpochQueryPlanScItemScopeCrossDomainMatchReq> matchReqList = Nullable.stream(scItemCodes).map(x->{
            EpochQueryPlanScItemScopeCrossDomainMatchReq request = new EpochQueryPlanScItemScopeCrossDomainMatchReq();
            request.setType(0);
            request.setScItemCode(x);
            return request;
        }).collect(Collectors.toList());
        Map<String, Object> reqMap = Maps.newHashMap();
        reqMap.put("arg0", matchReqList);
        log.info("SalesPlanScItemFileServiceImpl_query_plan_scitem_scope_cross_domain_match request:{}", JSONObject.toJSONString(reqMap));
        EpochQueryPlanScItemScopeCrossDomainMatchResp planScItemScopeResp = (EpochQueryPlanScItemScopeCrossDomainMatchResp)epochRESTClient.request(QUERY_PLAN_SCITEM_SCOPE_CROSS_DOMAIN_MATCH, reqMap, EpochQueryPlanScItemScopeCrossDomainMatchResp.class);
        log.info("SalesPlanScItemFileServiceImpl_query_plan_scitem_scope_cross_domain_match response:{}", JSONObject.toJSONString(planScItemScopeResp));
        if (planScItemScopeResp == null || CollectionUtils.isEmpty(planScItemScopeResp.getExistentList())) {
            return Result.success(ImportRequest.setRequestErrorMessage(requestList, ErrorMessage.code("OTS-02-001-00-15-043").getDisplayErrorMessage()));
        }
        List<String> existScItemCode = planScItemScopeResp.getExistentList().stream().map(EpochQueryPlanScItemScopeCrossDomainMatchReq::getScItemCode).collect(Collectors.toList());

        for (SalesPlanScItemImportRequest salesPlanScItemImportRequest : requestList) {
            //判空
            if (StringUtils.isBlank(salesPlanScItemImportRequest.getOrgBusinessUnitCode())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-009", null).getDisplayErrorMessage()));
                continue;
            }
            if (StringUtils.isBlank(salesPlanScItemImportRequest.getOrgSalesOrganizationCode())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-010", null).getDisplayErrorMessage()));
                continue;
            }
//            if (StringUtils.isBlank(salesPlanScItemImportRequest.getOrgSalesChannelCode())) {
//                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-011", null).getDisplayErrorMessage()));
//                continue;
//            }
            //计划货品范围优化 原销售渠道替换成业务渠道
            if (StringUtils.isBlank(salesPlanScItemImportRequest.getOrgBusinessChannelCode())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-003-01-15-030", null).getDisplayErrorMessage()));
                continue;
            }
            if (StringUtils.isBlank(salesPlanScItemImportRequest.getScItemId().trim())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-003", null).getDisplayErrorMessage()));
                continue;
            }
            //判断导入文件填写的业务单元是否存在
            if (organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgBusinessUnitCode()) == null
                    || !organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgBusinessUnitCode()).getType().equals(OrganizationTypeEnum.COMPANY.getCode())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-003-01-15-011", null).getDisplayErrorMessage()));
                continue;
            }
            //判断用户所属业务单元和导入文件中填写的业务单元是否匹配
//            if (!salesPlanScItemImportRequest.getOrgBusinessUnitCode().equals(userOrgBussinessUnitOutCode.get())) {
//                salesPlanScItemImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-003-01-15-016", null).getDisplayErrorMessage());
//                continue;
//            }
            //判断销售组织是否存在
            if (organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesOrganizationCode()) == null
                    || !organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesOrganizationCode()).getType().equals(OrganizationTypeEnum.SALES_ORGANIZATION.getCode())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-003-01-15-012", null).getDisplayErrorMessage()));
                continue;
            }
            //校验销售组织是否和业务单元匹配
            OrganizationSDO orgBusinessUnitSDO = organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgBusinessUnitCode());
            OrganizationSDO orgSalesOrgSDO = organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesOrganizationCode());
            if (!orgSalesOrgSDO.getParentId().equals(orgBusinessUnitSDO.getId())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-003-01-15-013", null).getDisplayErrorMessage()));
                continue;
            }
            ScItemSDO scItemSDO = scItemMap.get(salesPlanScItemImportRequest.getScItemId().trim());
            if (scItemSDO == null) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage()));
                continue;
            }
            //分子公司创建计划货品不可超出总部设置范围
            if (!existScItemCode.contains(salesPlanScItemImportRequest.getScItemId().trim())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-02-001-00-16-036").getDisplayErrorMessage()));
                continue;
            }

            //判断常规销售价是否存在
            if (StringUtils.isBlank(salesPlanScItemImportRequest.getCostInsuranceFreight())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-004", null).getDisplayErrorMessage()));
                continue;
            }
            //判断到岸价是否存在
            if (StringUtils.isBlank(salesPlanScItemImportRequest.getOutboundPrice())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-008", null).getDisplayErrorMessage()));
                continue;
            }

            //2022.08.02 不校验销售渠道 销售渠道替换为业务渠道
            //判断销售渠道是否存在
//            if (organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesChannelCode()) == null || !organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesChannelCode()).getType().equals(OrganizationTypeEnum.SALES_CHANNEL.getCode())) {
//                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-003-01-15-013", null).getDisplayErrorMessage()));
//                continue;
//            }
            //校验销售组织是否和销售渠道匹配
//            OrganizationSDO channelSDO = organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesChannelCode());
//            if (!channelSDO.getParentId().equals(organizationSDO.getId())) {
//                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-003-01-15-018", null).getDisplayErrorMessage()));
//                continue;
//            }
//            //判断级联关系
//            String id = organizationSDOMap.get(Optional.ofNullable(salesPlanScItemImportRequest.getOrgSalesChannelCode())).getId();
//            com.alibaba.lattice2.epoch.sdk.model.Result<List<TopOrganizationListResponse>> organizationResult = crPlatformEnhanceService.getTopOrganizationList(GetTopOrganizationListRequest.builder()
//                    .id(id).type(103).build());
//            if (!organizationResult.isSuccess() || CollectionUtils.isEmpty(organizationResult.getResult())) {
//                salesPlanScItemImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-003-01-15-017", null).getDisplayErrorMessage());
//                continue;
//            }
//            Map<String, Integer> organizationMap = organizationResult.getResult().stream().collect(Collectors.toMap(TopOrganizationListResponse::getCode, TopOrganizationListResponse::getType));
//            if (organizationMap.get(salesPlanScItemImportRequest.getOrgSalesOrganizationCode()) == null || !organizationMap.get(salesPlanScItemImportRequest.getOrgSalesOrganizationCode()).equals(OrganizationTypeEnum.SALES_ORGANIZATION.getCode())) {
//                salesPlanScItemImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-003-01-15-018", null).getDisplayErrorMessage());
//                continue;
//            } else {
//                if (organizationMap.get(salesPlanScItemImportRequest.getOrgBusinessUnitCode()) == null || !organizationMap.get(salesPlanScItemImportRequest.getOrgBusinessUnitCode()).equals(OrganizationTypeEnum.COMPANY.getCode())) {
//                    salesPlanScItemImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-003-01-15-019", null).getDisplayErrorMessage());
//                    continue;
//                }
//            }

            //导入excel无填写价格，去查价格表
            if(StringUtils.isBlank(salesPlanScItemImportRequest.getCostInsuranceFreight()) || StringUtils.isBlank(salesPlanScItemImportRequest.getOutboundPrice())){
                if(Objects.isNull(orgBusinessUnitSDO) || StringUtils.isBlank(orgBusinessUnitSDO.getBizId())){
                    salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-019", null).getDisplayErrorMessage()));
                    continue;
                }
                CustomerSaleScopeSDO customerSaleScopeSDO = customerSaleScopeMap.get(orgBusinessUnitSDO.getBizId());
                if(Objects.isNull(customerSaleScopeSDO)){
                    salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-019", null).getDisplayErrorMessage()));
                    continue;
                }

                //查询到岸价入参总部销售组织
                String superiorSalesOrgCode = superiorSalesOrgRelationMap.get(salesPlanScItemImportRequest.getOrgBusinessUnitCode());

                Map<String, ItemPriceResponse> priceMap = batchGetPrice(scItemSDO,customerSaleScopeSDO,orgSalesOrgSDO,salesPlanScItemImportRequest.getOrgBusinessChannelCode(),superiorSalesOrgCode);

                //常规销售价
                if(StringUtils.isBlank(salesPlanScItemImportRequest.getCostInsuranceFreight())){
                    ItemPriceResponse itemPriceResponse = priceMap.get(scItemSDO.getOuterId() + PriceTypeEnum.ZP01.getCode());
                    if(itemPriceResponse == null || itemPriceResponse.getMoneyAmout() == null){
                        salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-019", null).getDisplayErrorMessage()));
                        continue;
                    }
                    BigDecimal costInsuranceFreight = new BigDecimal(itemPriceResponse.getMoneyAmout()).divide(new BigDecimal(100),2,RoundingMode.HALF_UP);
                    salesPlanScItemImportRequest.setCostInsuranceFreight(costInsuranceFreight.toString());
                }
                //到岸价
                if(StringUtils.isBlank(salesPlanScItemImportRequest.getOutboundPrice())){
                    ItemPriceResponse itemPriceResponse = priceMap.get(scItemSDO.getOuterId() + PriceTypeEnum.ZMN1.getCode());
                    if(itemPriceResponse == null || itemPriceResponse.getMoneyAmout() == null){
                        salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-019", null).getDisplayErrorMessage()));
                        continue;
                    }
                    BigDecimal outboundPrice = new BigDecimal(itemPriceResponse.getMoneyAmout()).divide(new BigDecimal(100),2,RoundingMode.HALF_UP);
                    salesPlanScItemImportRequest.setOutboundPrice(outboundPrice.toString());
                }
            }

            try {
                //格式化价格 如果有误 报错出去，或者小于0也报错出去
                BigDecimal insuranceBd=new BigDecimal(salesPlanScItemImportRequest.getCostInsuranceFreight()).setScale(4,RoundingMode.HALF_UP);
                BigDecimal outboundPrice=new BigDecimal(salesPlanScItemImportRequest.getOutboundPrice()).setScale(4,RoundingMode.HALF_UP);

                if(insuranceBd.intValue()<0){
                    salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-018", null).getDisplayErrorMessage()));
                    continue;
                }
                if(outboundPrice.intValue()<0){
                    salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-018", null).getDisplayErrorMessage()));
                    continue;
                }
            }catch (Exception e){
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-018", null).getDisplayErrorMessage()));
                continue;
            }

            //判断平台是否存在这条数据
            SalesPlanScItemLoadListRequest scItemLoadListRequest = SalesPlanScItemLoadListRequest.newSalesPlanScItemLoadListRequestBuilder().build();
            scItemLoadListRequest.setOrgBusinessUnitCode(orgBusinessUnitSDO.getId());
            scItemLoadListRequest.setOrgSalesOrganizationCode(orgSalesOrgSDO.getId());
//            scItemLoadListRequest.setOrgSalesChannelCode(organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesChannelCode()).getId());
            scItemLoadListRequest.setOrgBusinessChannelCode(salesPlanScItemImportRequest.getOrgBusinessChannelCode());
            scItemLoadListRequest.setScItemId(scItemSDO.getScItemId());
            Result<List<SalesPlanScItem>> salesPlanScItemList = salesPlanScItemService.loadSalesPlanScItemList(scItemLoadListRequest);

            //填充数据
            SalesPlanScItem salesPlanScItem = new SalesPlanScItem();
            salesPlanScItem.setScItemId(scItemSDO.getScItemId());
            //类目
            String leafCategoryId = scItemSDO.getLeafCategoryId();
            if (StringUtils.isNotEmpty(leafCategoryId)) {
                QueryCategoryInfoByIdsRequest build = QueryCategoryInfoByIdsRequest.builder().categoryIdList(Lists.newArrayList(leafCategoryId)).build();
                com.alibaba.lattice2.epoch.sdk.model.Result<List<CategorySDO>> listResult = baseDataService.queryCategoryInfoByIds(build);
                if (listResult != null && listResult.isSuccess() && listResult.getResult() != null) {
                    CategorySDO categorySDO = listResult.getResult().stream().findFirst().get();
                    if (categorySDO.getRoot()) {
                        //该类目是根节点
                        salesPlanScItem.setScItemRootCategoryId(categorySDO.getRootCategoryId());
                    } else {
                        //叶子节点
                        salesPlanScItem.setScItemLeafCategoryId(categorySDO.getCategoryId());
                        salesPlanScItem.setScItemRootCategoryId(categorySDO.getRootCategoryId());
                    }
                }
            }
            salesPlanScItem.setOrgBusinessUnitCode(orgBusinessUnitSDO.getId());
            salesPlanScItem.setOrgSalesOrganizationCode(orgSalesOrgSDO.getId());
//            salesPlanScItem.setOrgSalesChannelCode(organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesChannelCode()).getId());
            salesPlanScItem.setOrgBusinessChannelCode(salesPlanScItemImportRequest.getOrgBusinessChannelCode());

            BigDecimal insuranceBd=new BigDecimal(salesPlanScItemImportRequest.getCostInsuranceFreight()).setScale(2,RoundingMode.HALF_UP);
            BigDecimal multy100=new BigDecimal(100);
            salesPlanScItem.setCostInsuranceFreight(insuranceBd.multiply(multy100).longValue());
            BigDecimal outboundPrice=new BigDecimal(salesPlanScItemImportRequest.getOutboundPrice()).setScale(2,RoundingMode.HALF_UP);
            salesPlanScItem.setOutboundPrice(outboundPrice.multiply(multy100).longValue());
            //禁用状态
            salesPlanScItem.setMark(salesPlanScItemImportRequest.getMark());
            if (Objects.isNull(salesPlanScItemImportRequest.getStatus())) {
                salesPlanScItem.setStatus(1);
            } else {
                salesPlanScItem.setStatus(salesPlanScItemImportRequest.getStatus());
            }

            if (salesPlanScItemList == null || CollectionUtils.isEmpty(salesPlanScItemList.getResult())) {
                salesPlanScItem.setGmt_create(new Date());
                salesPlanScItem.setGmt_modified(new Date());
                addRequest.add(salesPlanScItem);
            } else {
                SalesPlanScItem item = salesPlanScItemList.getResult().stream().findFirst().get();
                salesPlanScItem.setStatus(1);
                salesPlanScItem.setId(item.getId());
                salesPlanScItem.setGmt_modified(new Date());
                salesPlanScItemService.updateSalesPlanScItem(salesPlanScItem);
                updateRequest.add(salesPlanScItem);
            }
        }
        if (CollectionUtils.isNotEmpty(addRequest)) {
            //批量新增和批量更新
            BatchCreateSalesPlanScItemRequest salesPlanScItemRequest = new BatchCreateSalesPlanScItemRequest();
            salesPlanScItemRequest.setRequestList(addRequest);
            BatchCreateSalesPlanScItemResponse batchCreateSalesPlanScItemResponse = salesPlanScItemService.batchCreateSalesPlanScItem(salesPlanScItemRequest);
        }

        return Result.success(requestList);
    }

    private Map<String,CustomerSaleScopeSDO> batchGetCustomerSaleScope(List<OrganizationSDO> orgBusinessUnitSDOList) {
        if(CollectionUtils.isEmpty(orgBusinessUnitSDOList)){
            return new HashMap<>();
        }
        //查询公司获取customerCodes
        List<String> bizIdList = orgBusinessUnitSDOList.stream()
                .filter(x-> org.apache.commons.lang3.StringUtils.isNotBlank(x.getBizId()))
                .map(x->x.getBizId()).collect(Collectors.toList());
        List<CompanySDO> companySDOS = batchQueryCompany(bizIdList);
        List<String> companyCodeList = companySDOS.stream().map(x->x.getOutCode()).collect(Collectors.toList());

        //事业部6000、6004组织
        Result<QuerySuperiorSalesOrganizationResponse> groupOrgResult = organizationQueryService.queryEnterpriseGroupOrg();

        List<CustomerSaleScopeSDO> queryCustomerSaleScopes =  new ArrayList();
        //查询售达方
        QuerySaleScopeRequest querySaleScopeRequest = QuerySaleScopeRequest.newQuerySaleScopeRequestBuilder()
                .customerCodeList(companyCodeList)
                .orgSaleOrganizationCode(groupOrgResult.getResult().getEnterpriseGroup().getId())
                .itemGroup("11")
                .channelCode("20")
                .build();
        querySaleScopeRequest.setLimit(1000);
        Result<List<CustomerSaleScopeSDO>> result = customerSaleScopeQueryService.pageQuerySaleScope(querySaleScopeRequest);
        if(result != null && CollectionUtils.isNotEmpty(result.getResult())){
            result.getResult().forEach(x->{x.setOrgSalesOrganizationCode2(OrganizationConstants.ENTERPRISE_GROUP_CODE);});
            queryCustomerSaleScopes.addAll(result.getResult());
        }

        QuerySaleScopeRequest querySaleScopeRequest2 = QuerySaleScopeRequest.newQuerySaleScopeRequestBuilder()
                .customerCodeList(companyCodeList)
                .orgSaleOrganizationCode(groupOrgResult.getResult().getXinJiangCompany().getId())
                .itemGroup("11")
                .channelCode("20")
                .build();
        querySaleScopeRequest.setLimit(1000);
        Result<List<CustomerSaleScopeSDO>> result2 = customerSaleScopeQueryService.pageQuerySaleScope(querySaleScopeRequest2);
        if(result2 != null && CollectionUtils.isNotEmpty(result2.getResult())){
            result2.getResult().forEach(x->{x.setOrgSalesOrganizationCode2(OrganizationConstants.XINJIANG_COMPANY_CODE);});
            queryCustomerSaleScopes.addAll(result2.getResult());
        }

        Map<String,CustomerSaleScopeSDO> resultMap = new HashMap<>();
        if (CollectionUtils.isEmpty(queryCustomerSaleScopes)) {
            return resultMap;
        }
        Map<String,CustomerSaleScopeSDO> customerSaleScopeMap = queryCustomerSaleScopes.stream().collect(Collectors.toMap(CustomerSaleScopeSDO::getCustomerCode, Function.identity(),(v1, v2)->v1));
        Nullable.stream(companySDOS).forEach(x->{
            CustomerSaleScopeSDO sdo = customerSaleScopeMap.get(x.getOutCode());
            if(sdo != null){
                resultMap.put(x.getId(),sdo);
            }
        });
        return resultMap;
    }

    private Map<String,String> batchGetSuperiorSalesOrg(Set<String> orgBusinessUnitCodeList) {
        if(CollectionUtils.isEmpty(orgBusinessUnitCodeList)){
            return new HashMap<>();
        }
        BatchQuerySuperiorSalesOrganizationRequest batchQuerySuperiorSalesOrganizationRequest = new BatchQuerySuperiorSalesOrganizationRequest();
        batchQuerySuperiorSalesOrganizationRequest.setOrganizationCodes(Lists.newArrayList(orgBusinessUnitCodeList));
        Result<QuerySuperiorSalesOrganizationResponse> querySuperiorSalesOrganizationResponse = organizationQueryService.batchQuerySuperiorSalesOrganization(batchQuerySuperiorSalesOrganizationRequest);
        Map<String,String> relationMap = querySuperiorSalesOrganizationResponse.getResult().getRelationMap();
        return relationMap;
    }

    private List<CompanySDO> batchQueryCompany(List companyIdList){
        if(CollectionUtils.isEmpty(companyIdList)){
            return new ArrayList<>();
        }
        BatchQueryCompany2Request companyRequest = new BatchQueryCompany2Request();
        companyRequest.setIds(companyIdList);
        Result<List<CompanySDO>> result = bcOrderService.batchQueryCompany2(companyRequest);
        if(result == null || CollectionUtils.isEmpty(result.getResult())){
            return new ArrayList<>();
        }
        return result.getResult().stream().filter(x->org.apache.commons.lang3.StringUtils.isNotBlank(x.getOutCode())).collect(Collectors.toList());
    }

    private Map<String, ItemPriceResponse> batchGetPrice(ScItemSDO scItemSDO, CustomerSaleScopeSDO customerSaleScopeSDO,OrganizationSDO orgSalesOrgSDO, String orgBusinessChannelCode, String superiorSalesOrgCode){
        List<DimensionPropertyInfoRequest> dimensionPropertyInfoRequestList = Lists.newArrayList();
        // 常规价请求
        DimensionPropertyInfoRequest propertyInfoRequest = buildCommonSalesPrice(scItemSDO, orgSalesOrgSDO, orgBusinessChannelCode);
        // 到岸价请求
        DimensionPropertyInfoRequest propertyInfoRequest2 = buildCFIPrice(scItemSDO, customerSaleScopeSDO, superiorSalesOrgCode, orgBusinessChannelCode);
        dimensionPropertyInfoRequestList.add(propertyInfoRequest);
        dimensionPropertyInfoRequestList.add(propertyInfoRequest2);

        PriceQueryRequest priceQueryRequest = new PriceQueryRequest();
        priceQueryRequest.setDimensionPropertyInfoRequestList(dimensionPropertyInfoRequestList);
        Map<String, String> featuresMap = Maps.newHashMap();
        featuresMap.put("outCodeToInnerCode", "out_code_to_inner_code");
        priceQueryRequest.setFeatures(featuresMap);
        Result<PriceQueryResponse> priceQueryResponseResult = priceQueryService.batchQueryPrice(priceQueryRequest);
        log.info("salesPlanScItemFileServiceImpl_batchQueryPrice_request={},result={}", JSONObject.toJSON(priceQueryRequest),JSONObject.toJSON(priceQueryResponseResult));

        Map<String, ItemPriceResponse> itemPriceResponseMap = Nullable.stream(priceQueryResponseResult.getResult().getItemPriceResponseList())
                .filter(x -> (null != x.getMoneyAmout() && x.getMoneyAmout() > 0 && null != x.getFeatures().get("priceType")))
                .collect(Collectors.toMap(x -> x.getItemId() + x.getFeatures().get("priceType"), a -> a, (a, b) -> a));
        return itemPriceResponseMap;
    }

    private DimensionPropertyInfoRequest buildCommonSalesPrice(ScItemSDO scItemSDO, OrganizationSDO orgSalesOrgSDO, String orgBusinessChannelCode) {
        // 组装 货品请求数据
        MaterialInfoRequest materialInfoRequest = new MaterialInfoRequest();
        materialInfoRequest.setMaterialCode(scItemSDO.getOuterId());
        materialInfoRequest.setScItemGroupCode("11");
        // 组织 组织请求数据
        PlaceInfoRequest placeInfoRequest = new PlaceInfoRequest();
        placeInfoRequest.setSalesUnitCode(Optional.ofNullable(scItemSDO.getFeatures().get("unitName")).map(String::valueOf).orElse(null));
        placeInfoRequest.setOrgSalesOrganizationCode(orgSalesOrgSDO.getOutCode());
        //计划货品范围优化版本 -- 根据业务渠道获取价格
        placeInfoRequest.setChannelCode(orgBusinessChannelCode);

        // 请求查询价格参数
        DimensionPropertyInfoRequest propertyInfoRequest = new DimensionPropertyInfoRequest();
        propertyInfoRequest.setPriceTypeId(PriceTypeEnum.ZP01.getCode());
        propertyInfoRequest.setPriceUseDate(new Date());
        propertyInfoRequest.setMaterialInfoRequest(materialInfoRequest);
        propertyInfoRequest.setPlaceInfoRequest(placeInfoRequest);
        propertyInfoRequest.setHumanInfoRequest(new HumanInfoRequest());
        return propertyInfoRequest;
    }

    private DimensionPropertyInfoRequest buildCFIPrice(ScItemSDO scItemSDO, CustomerSaleScopeSDO customerSaleScopeSDO, String superiorSalesOrgCode, String orgBusinessChannelCode) {
        // 组装 货品请求数据
        MaterialInfoRequest materialInfoRequest2 = new MaterialInfoRequest();
        // 货品
        materialInfoRequest2.setMaterialCode(scItemSDO.getOuterId());
        // 货品组
        materialInfoRequest2.setScItemGroupCode("11");

        // 组织 组织请求数据
        PlaceInfoRequest placeInfoRequest2 = new PlaceInfoRequest();

        // 销售组织
        placeInfoRequest2.setOrgSalesOrganizationCode(superiorSalesOrgCode);

        // SAP工厂
        placeInfoRequest2.setFactoryCode(Optional.ofNullable(customerSaleScopeSDO.getStoreHouse()).orElse(null));
        // 销售渠道
//        placeInfoRequest2.setSalesDepartment(Optional.ofNullable(customerSaleScopeSDO.getOutOrgSalesChannelCode()).orElse(null));
        // 业务渠道
//        placeInfoRequest2.setChannelCode("20");
        //计划货品范围版本优化 -- 根据业务渠道获取价格 原来的销售渠道不用
        placeInfoRequest2.setChannelCode(orgBusinessChannelCode);
        // 销售部门
        placeInfoRequest2.setSalesGroup(Optional.ofNullable(customerSaleScopeSDO.getOutOrgSalesDepartmentCode()).orElse(null));
        // 部门
        placeInfoRequest2.setDepartmentCode(Optional.ofNullable(customerSaleScopeSDO.getOutOrgSalesChannelCode()).orElse(null));
        // 定价区域
        placeInfoRequest2.setPriceArea(Optional.ofNullable(customerSaleScopeSDO.getSalesArea()).orElse(null));

        HumanInfoRequest humanInfoRequest2 = new HumanInfoRequest();
        // 客户
        humanInfoRequest2.setCustomerCode(Optional.ofNullable(customerSaleScopeSDO.getCustomerCode()).orElse(null));

        // 请求查询价格参数
        DimensionPropertyInfoRequest propertyInfoRequest2 = new DimensionPropertyInfoRequest();
        propertyInfoRequest2.setPriceTypeId(PriceTypeEnum.ZMN1.getCode());
        propertyInfoRequest2.setPriceUseDate(new Date());
        propertyInfoRequest2.setMaterialInfoRequest(materialInfoRequest2);
        propertyInfoRequest2.setPlaceInfoRequest(placeInfoRequest2);
        propertyInfoRequest2.setHumanInfoRequest(humanInfoRequest2);
        return propertyInfoRequest2;
    }

}
